﻿using ChuanYe.Commom;
using ChuanYe.IBLL;
using ChuanYe.Models;
using ChuanYe.Models.Model;
using ChuanYe.Utils;
using Microsoft.Practices.Unity;
using SJPlatForm.Web.Models;
using SJPlatForm.Web.Models.FuDi;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Cryptography;
using System.Web;
using System.Web.Http;
using System.Web.Http.Cors;

namespace SJPlatForm.Web.Controllers
{

    /// <summary>
    /// 用于配合 富地 API
    /// </summary>
    [EnableCors("*", "*", "*")]
    class GEOController : ApiController
    {

        #region 依赖注入及配置文件路径

        /// <summary>
        /// 城市地名依赖块
        /// </summary>
        [Dependency]
        public IFireInfoBLL bll { get; set; }

        /// <summary>
        /// 市局区县地区业务块
        /// </summary>
        [Dependency]
        public ILinchpinBLL linchpinBll { get; set; }

        /// <summary>
        /// 用户信息依赖块
        /// </summary>
        [Dependency]
        public IUsersInfosBLL userInfoBll { get; set; }

        /// <summary>
        /// 用户信息依赖块
        /// </summary>
        [Dependency]
        public IMemberInfoBLL memberInfoBll { get; set; }

        /// <summary>
        /// 火灾统计块
        /// </summary>
        [Dependency]
        public IFireStatisticsBLL fireStatisticsBLL { get; set; }


        /// <summary>
        /// 物资管理
        /// </summary>
        [Dependency]
        public IGoodsManageBLL goodsManageBLL { get; set; }


        #endregion


        /// <summary>
        ///  登录
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost]
        public ResultDto<dynamic> Login(LoginReq obj)
        {
            ResultDto<dynamic> result = new ResultDto<dynamic>();
            try
            {
                //验证参数是否完整
                if (obj == null || string.IsNullOrEmpty(obj.UserCode) || string.IsNullOrEmpty(obj.PassWord))
                {
                    result.Status = 0;
                    result.Message = "Missing Required Parameters";
                    return result;
                }
                var existUserInfo = userInfoBll.Login(obj.UserCode);

                //验证账号是否存在
                if (existUserInfo == null)
                {
                    result.Status = 0;
                    result.Message = "The UserCode Is Null";
                    return result;
                }

                //验证是否密码匹配
                if (existUserInfo.PassWord.ToLower() != obj.PassWord.ToLower())
                {
                    result.Status = 0;
                    result.Message = "The PassWord Is Error";
                    return result;
                }

                //验证是否冻结
                if (existUserInfo.IsDisable != null && existUserInfo.IsDisable.Value == true)
                {
                    result.Status = 0;
                    result.Message = "Account Has Been Frozen";
                    return result;
                }

                //加载用户权限
                var powersList = userInfoBll.GetPower(existUserInfo.RoleID.Value);
                existUserInfo.Powers = powersList;
                existUserInfo.IsLogin = true;
                existUserInfo.AES_KEY = SJPlatForm.Web.Common.ConfigHelper.AES_KEY;
                int roleType = 0;
                foreach (var item in powersList)
                {
                    if (item.Power_ID == "SJ100000")
                    {
                        roleType = 1;
                    }
                    else if (item.Power_ID == "QX100000")
                    {
                        roleType = 2;
                    }
                }


                SundryHelper.SetCache<LoginUserModel>(existUserInfo.ID.ToString(), existUserInfo, int.MaxValue);
                var data = new {
                    Token = existUserInfo.ID.ToString(),
                    TimeStamp = ValueConvert.DateTimeToTimeStamp(DateTime.Now),
                    Powers = existUserInfo.Powers,
                    UserName = existUserInfo.UserName,
                    RoleName = existUserInfo.RoleName,
                    AES_KEY = existUserInfo.AES_KEY,
                    Address = existUserInfo.Address,
                    IsManager = existUserInfo.IsManager,
                    DepID = existUserInfo.DepID == null ? 0 : existUserInfo.DepID.Value,
                    RoleType= roleType,
                };
                result.FirstParam = data;
                result.Status = 1;
                result.Message = "The PassWord Is Error";
            }
            catch (Exception ex)
            {
                result.Status = 500;
                result.Message = "FuDiController Login Server Error";
                Log.Error("FuDiController Login ", ex.ToString());
            }
            return result;
        }

        #region 火灾列表
        /// <summary>
        /// (市局+区县)--火灾列表
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost]
        public ResultDto<dynamic, int> GetFireInfoByPage(FireInfoReq obj)
        {
            ResultDto<dynamic, int> result = new ResultDto<dynamic, int>();
            List<F_FireInfo> list = null;
            try
            {
                GridPager2 pager = Pickout.GetGridPager2(obj);
                if (pager.StartTime != null)
                {
                    pager.StartTime = pager.StartTime.StateTimeConvert();
                }
                if (pager.EndTime != null)
                {
                    pager.EndTime = pager.EndTime.EndTimeConvert();
                }
                list = bll.ListByPager(obj.AddressCountys, obj.FireSate, pager);

                List<int> fireIDs = list.Select(s => s.F_FireID).ToList();

                //2018-12-04 增加逻辑，区县不显示文档
                //如果 obj.AddressCountys 如果不为空，即设定为区县调用
                int searchLevel = obj.AddressCountys != null && obj.AddressCountys.Length > 0 ? 1 : 0;
                var mrList = bll.MRListByFireIDs(fireIDs, searchLevel);
                var finalList = bll.GetFireFinalReport(fireIDs);
                var videoList = bll.GetFireAttachs(fireIDs);
                List<DirectorysTb> dtbList = memberInfoBll.GetDirectorysTb(2);
                var data = from info in list
                           join mr in mrList
                           on info.F_FireID equals mr.F_FireID
                           into a
                           from b in a.DefaultIfEmpty()
                           join f in finalList on info.F_FireID equals f.F_FireID
                           into e
                           from g in e.DefaultIfEmpty()
                           select new
                           {
                               info.F_FireID,
                               info.F_Address,
                               info.F_FireName,
                               info.F_ReporterPhone,
                               info.F_ReporterName,
                               info.F_ReporterUnit,
                               info.F_HappenDatetime,
                               info.F_AlarmTime,
                               info.F_AddressCounty,
                               MR_Type = b == null ? null : b.MR_Type,
                               MR_Message = b == null ? string.Empty : Pickout.GetMRecordTypeText(b.MR_Type.Value),
                               FFR_Why = g == null ? null : g.FFR_Why,
                               FFR_Type = g == null ? null : g.FFR_Type,
                               FFR_TypeName = g == null ? null : (dtbList.Where(p => p.id == g.FFR_Type).FirstOrDefault() == null ? string.Empty :
                                                           dtbList.Where(p => p.id == g.FFR_Type).FirstOrDefault().DName),
                               IsExistVideo = videoList.Where(p => p.F_FireID == info.F_FireID).Count() > 0 ? 1 : 0,
                               info.F_IsHb,
                           };
                var temp = data.ToList();
                //获取续报终报消息是否得到回复
                var maList = bll.GetFireAutomatic(fireIDs, new List<int>() { });
                List<dynamic> res = new List<dynamic>();
                foreach (var item in data)
                {
                    string color = "red";
                    //判定状态字体颜色
                    if (item.MR_Type != null && item.MR_Type == 2)
                    {
                        //首报属于过期状态
                        var tempData = maList.Where(p => p.F_FireID == item.F_FireID && p.M_Type == 17).FirstOrDefault();
                        color = tempData == null ? "green" : "red";
                    }
                    else if (item.MR_Type != null && item.MR_Type == 5)
                    {
                        //续报属于过期状态
                        var tempData = maList.Where(p => p.F_FireID == item.F_FireID && p.M_Type == 18).FirstOrDefault();
                        color = tempData == null ? "green" : "red";
                    }
                    else if (item.MR_Type != null && item.MR_Type == 17)
                    {
                        //终报属于过期状态
                        var tempData = maList.Where(p => p.F_FireID == item.F_FireID && p.M_Type == 19).FirstOrDefault();
                        color = tempData == null ? "green" : "red";
                    }
                    else
                    {
                        color = "red";
                    }
                    res.Add(new
                    {
                        F_FireID = item.F_FireID,
                        F_Address = item.F_Address,
                        F_FireName = item.F_FireName,
                        F_ReporterPhone = item.F_ReporterPhone,
                        F_ReporterName = item.F_ReporterName,
                        F_ReporterUnit = item.F_ReporterUnit,
                        F_HappenDatetime = item.F_HappenDatetime,
                        F_AlarmTime = item.F_AlarmTime,
                        F_AddressCounty = item.F_AddressCounty,
                        MR_Type = item.MR_Type,
                        MR_Message = item.MR_Message,
                        Color = color,
                        FFR_Why = item.FFR_Why,
                        IsExistVideo = item.IsExistVideo,
                        F_IsHb = item.F_IsHb == null ? 0 : item.F_IsHb,
                        FFR_Type = item.FFR_Type,
                        FFR_TypeName = item.FFR_TypeName
                    });
                }

                result.FirstParam = res;
                result.SecondParam = pager.TotalRows;
                result.Status = 1;
                result.Message = "Request Is Success";
            }
            catch (Exception ex)
            {
                result.Status = 500;
                result.Message = "FireInfoController GetFireInfoByPager Server Error";
                Log.Error("FireInfoController GetFireInfoByPager", ex.ToString());
            }
            return result;
        }
        #endregion


        /// <summary>
        /// 火灾明细
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost]
        public ResultDto<dynamic> GetFireDetail(FireDetailReq obj)
        {
            ResultDto<dynamic> result = new ResultDto<dynamic>();
            try
            {
                if (obj != null)
                {
                    //火灾信息
                    F_FireInfo fireInfo = bll.FireInfoDetail(obj.FireID);

                    if (fireInfo == null)
                    {
                        result.Status = 0;
                        result.Message = "The FireInfo Is Null";
                        return result;
                    }
                    //首报
                    F_FireFirstReport ffrInfo = bll.FireFirstReportDetail(obj.FireID);
                    //续报
                    List<F_FireContinueReport> continueReportInfo = bll.GetFireContinueReport(obj.FireID);
                    //火灾转场信息
                    F_FireTransField fftInfo = bll.FireTransFieldDetail(obj.FireID);
                    //定位火点
                    List<F_FireSite> fsList = bll.GetFireSiteInfoByFireID(obj.FireID);
                    //记录文档
                    List<F_FireDocumentation> fdList = bll.GetFireDocumentation(obj.FireID);

                    List<int> fdTransUserIds = fdList.Where(p => !string.IsNullOrEmpty(p.FD_TransUser))
                                                     .Select(s => s.FD_TransUser).ToList().Select<string, int>(s => Convert.ToInt32(s)).ToList();
                    List<UsersInfos> fdUserInfosList = userInfoBll.GetUserInfos(fdTransUserIds);

                    List<dynamic> fdresList = new List<dynamic>();
                    for (int i = 0; i < fdList.Count; i++)
                    {
                        var temp = fdUserInfosList.Where(p => p.ID == Convert.ToInt32(fdList[i].FD_TransUser)).FirstOrDefault();
                        fdresList.Add(new
                        {
                            FD_ID = fdList[i].FD_ID,
                            FD_MessageTime = fdList[i].FD_MessageTime,
                            FD_MessageContent = fdList[i].FD_MessageContent,
                            FD_TransUser = temp != null ? temp.UserName : string.Empty
                        });
                    }

                    //成立前指
                    #region 成立前指 
                    List<F_FrontCommand> list = bll.GetFrontCommand(obj.FireID);
                    List<string> tempList = list.Select(s => s.FC_Member).ToList();
                    List<int> mIdList = new List<int>();
                    for (int i = 0; i < tempList.Count; i++)
                    {
                        string mIDsStr = tempList[i];
                        if (mIDsStr.IndexOf(",") != -1)
                        {
                            string[] mids = mIDsStr.Split(',');
                            for (int j = 0; j < mids.Length; j++)
                            {
                                mIdList.Add(mids[j].ToInt());
                            }
                        }
                        else
                        {
                            mIdList.Add(mIDsStr.ToInt());
                        }
                    }
                    mIdList = mIdList.Distinct().ToList();
                    List<F_MemberInfo> mList = memberInfoBll.GetMemberInfo(mIdList);
                    F_FrontCommand fcInfo = list.FirstOrDefault();
                    if (fcInfo != null)
                    {
                        fcInfo.FC_Member = string.Join(",", mList.Select(s => s.M_MemberName).ToList());
                    }
                    #endregion
                    //逐级响应
                    F_StepResponse stepResponse = bll.StepResponseDetail(obj.FireID);
                    //扑救力量
                    List<F_FightingForce> ffList = bll.GetFightingForce(obj.FireID);

                    //联动响应
                    #region 联动响应
                    List<F_Response> responseList = bll.GetResponse(obj.FireID);
                    List<LinkCorresponding> linkCorresList = memberInfoBll.GetLinkCorresponding();


                    List<dynamic> respnseDepList = new List<dynamic>();
                    foreach (var item in responseList)
                    {
                        if (item != null && !string.IsNullOrEmpty(item.Res_UnitID) && item.Res_UnitID.IndexOf(',') > -1)
                        {
                            string[] uids = item.Res_UnitID.Split(',');
                            List<int> uidList = uids.Select(s => Convert.ToInt32(s)).ToList();
                            List<string> deps = linkCorresList.Where(p => uidList.Contains(p.ID)).Select(s => s.DepartMent).Distinct().ToList();
                            string deps_Str = string.Join(",", deps);
                            respnseDepList.Add(new { ID = item.Res_ID, DepartMent = deps_Str, HandleTime = item.Res_HandleTime });
                        }
                    }
                    #endregion

                    //火灾误报
                    List<Catalog> catalogInfoList = bll.GetFireCatalog(obj.FireID);
                    //火灾报灭
                    F_ReportOutFire fireReportOutInfo = bll.FireReportOutDetail(obj.FireID);
                    //处置记录
                    var pager = new GridPager2();
                    pager.PageSize = int.MaxValue;
                    pager.PageIndex = 1;
                    List<M_Record> rinfoList = bll.MRListByFireID(obj.FireID, pager);
                    //火灾询问与回答
                    var askInfoList = bll.FireAskAndAnswer(obj.FireID);
                    //扑救处置记录
                    List<M_Record> fffInfoList = rinfoList.Where(p => p.MR_Type == (int)RecordType.市局调集扑救力量).OrderBy(o => o.CFA_ID).ToList();

                    //火灾终报
                    F_FireFinalReport finalReportInfo = bll.FireFinalReportDetail(obj.FireID);

                    //火灾类型 起火原因等集合
                    List<DirectorysTb> dtbList = memberInfoBll.GetDirectorysTb(0);

                    var data = new
                    {
                        FireInfo = fireInfo,
                        FireFirstReport = ffrInfo,
                        ContinueReport = continueReportInfo,
                        FireTransField = fftInfo,
                        FireSite = fsList,
                        FireDocumentation = fdresList,
                        FrontCommand = fcInfo,
                        StepResponse = stepResponse,
                        FightingForce = ffList,
                        FightingForce2 = fffInfoList,
                        Response = respnseDepList,
                        Catalog = catalogInfoList,
                        ReportOutFire = fireReportOutInfo,
                        FireFinalReport = finalReportInfo,
                    };
                    result.FirstParam = data;
                    result.Status = 1;
                    result.Message = "Request Is Success";
                }
                else
                {
                    result.Status = 0;
                    result.Message = "Missing Required Parameters";
                }
            }
            catch (Exception ex)
            {
                result.Status = 500;
                result.Message = "FuDiController GetFireDetail Server Error";
                Log.Error("FuDiController GetFireDetail ", ex.ToString());
            }
            return result;
        }


        /// <summary>
        /// 返回当前火灾状态
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost]
        public ResultDto<dynamic> GetFireState(FireDetailReq obj)
        {
            ResultDto<dynamic> result = new ResultDto<dynamic>();
            try
            {
                if (obj != null)
                {
                    var mrList = bll.MRListByFireIDs(new List<int>() { obj.FireID });

                    if (mrList == null && mrList.Count==0)
                    {
                        result.Status = 0;
                        result.Message = "The FireID Data Is Null";
                        return result;
                    }
                    string value = string.Empty;
                    int key = 0;
                    foreach (int myCode in Enum.GetValues(typeof(RecordType)))
                    {
                       
                        if (myCode == mrList.FirstOrDefault().MR_Type)
                        {
                            key = myCode;//获取值
                            value = Enum.GetName(typeof(RecordType), myCode);//获取名称
                            break;
                        }
                    }
                    result.FirstParam = new {FireID=obj.FireID, Key=key,Value=value  };
                    result.Status = 1;
                    result.Message = "Request Is Success";
                }
                else
                {
                    result.Status = 0;
                    result.Message = "Missing Required Parameters";
                }
            }
            catch (Exception ex)
            {
                result.Status = 500;
                result.Message = "FuDiController GetFireState Server Error";
                Log.Error("FuDiController GetFireState", ex.ToString());
            }
            return result;
        }

        /// <summary>
        /// 态势图上传接口 
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost]
        public ResultDto<dynamic> SituationUpload(UpLoadReq obj)
        {
            ResultDto<dynamic> result = new ResultDto<dynamic>();
            try
            {
                if (obj != null)
                {
                    string filePath = string.Empty;
                    string fileName = string.Empty;
                    //string savePath = HttpContext.Current.Server.MapPath("~/");
                    string savePath = AppDomain.CurrentDomain.BaseDirectory;
                    string folderName = "FuDi/Situation/";
                    switch (obj.FileType)
                    {
                        case (1): folderName += "Images/"; break;
                        case (2): folderName += "Files/"; break;
                        case (3): folderName += "Videos/"; break;
                        default: folderName += "Images/"; break;
                    }
                    savePath += folderName;

                    byte[] ibyte = FileConvertUtil.FromBase64ToByte(obj.FileByte);
                    MD5 md5 = new MD5CryptoServiceProvider();
                    byte[] fileKey = md5.ComputeHash(ibyte);
                    string md5Ibyte = Convert.ToBase64String(fileKey);
                    md5Ibyte = md5Ibyte.Replace('/', 'f');
                    md5Ibyte = md5Ibyte.Replace('@', 'w');
                    md5Ibyte = md5Ibyte.Replace('+', 'y');
                    md5Ibyte = md5Ibyte.Replace(' ', 'j');
                    md5Ibyte = md5Ibyte.Replace('.', 'x');
                    md5Ibyte = md5Ibyte.Replace('\\', 'd');
                    md5Ibyte = md5Ibyte.Substring(0, 19);
                    filePath = md5Ibyte.Substring(0, 4) + "/" +
                               md5Ibyte.Substring(4, 3) + "/" +
                               md5Ibyte.Substring(7, 4);

                    fileName = md5Ibyte.Substring(11) + "." + obj.ExtName;
                    string fullName = savePath + "/" + filePath + "/";

                    if (!Directory.Exists(fullName))
                    {
                        Directory.CreateDirectory(fullName);
                    }

                    using (FileStream deflultStream = new System.IO.FileStream(fullName + fileName, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite))
                    {
                        deflultStream.Write(ibyte, 0, ibyte.Length);
                        deflultStream.Close();
                    }
                    //态势图保存
                    string serverFullPath= folderName + filePath + "/" + fileName;

                    F_FireSituation fs = new F_FireSituation() {
                        F_FireID = obj.FireID,
                        F_FireState = obj.FireState,
                        FS_FilePath = serverFullPath,
                        FS_TransTime = DateTime.Now
                    };

                    if (bll.UpdateFireSituation(fs) <= 0)
                    {
                        bll.AddFireSituation(fs);
                    }

                    result.FirstParam = serverFullPath;
                    result.Status = 1;
                    result.Message = "Request Is Success";
                }
                else
                {
                    result.Status = 0;
                    result.Message = "Missing Required Parameters";
                }
            }
            catch (Exception ex)
            {
                result.Status = 500;
                result.Message = "FuDiController SituationUpload Server Error";
                Log.Error("FuDiController SituationUpload ", ex.ToString());
            }
            return result;
        }


        /// <summary>
        ///  物资仓库信息列表
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost]
        public ResultDto<dynamic> GetWarehouse(WarehouseReq obj)
        {
            ResultDto<dynamic> result = new ResultDto<dynamic>();
            try
            {
                if (obj != null)
                {
                    W_Warehouse info = new W_Warehouse() {
                        WH_ID = obj.ID,
                        WH_Name =obj.Name,
                        WH_Address=obj.Address,
                        WH_Capacity=obj.Capacity,
                        WH_Longitude=obj.Longitude,
                        WH_Latitude=obj.Latitude,
                        Entity_ID=obj.Entity_ID,
                        Entity_Name=obj.Entity_Name,
                        WH_Phone=obj.Phone,
                        WH_Photo=obj.Photo,
                        WH_Spell=obj.Spell,
                        WH_TransDatetime=DateTime.Now
                    };
                    List<W_Warehouse> list= goodsManageBLL.GetWarehouse(info);
                    result.FirstParam = list;
                    result.Status = 1;
                    result.Message = "Request Is Success";
                }
                else
                {
                    result.Status = 0;
                    result.Message = "Missing Required Parameters";
                }
            }
            catch (Exception ex)
            {
                result.Status = 500;
                result.Message = "FuDiController GetWarehouse Server Error";
                Log.Error("FuDiController Demo ", ex.ToString());
            }
            return result;
        }

        /// <summary>
        ///  物资仓库信息列表 分页
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost]
        public ResultDto<dynamic> GetWarehouseByPage(WarehouseReq obj)
        {
            ResultDto<dynamic> result = new ResultDto<dynamic>();
            try
            {
                if (obj != null)
                {

                    GridPager2 pager = Pickout.GetGridPager2(obj);
                    if (pager.StartTime != null)
                    {
                        pager.StartTime = pager.StartTime.StateTimeConvert();
                    }
                    if (pager.EndTime != null)
                    {
                        pager.EndTime = pager.EndTime.EndTimeConvert();
                    }

                    W_Warehouse info = new W_Warehouse()
                    {
                        WH_ID=obj.ID,
                        WH_Name = obj.Name,
                        WH_Address = obj.Address,
                        WH_Capacity = obj.Capacity,
                        WH_Longitude = obj.Longitude,
                        WH_Latitude = obj.Latitude,
                        Entity_ID = obj.Entity_ID,
                        Entity_Name = obj.Entity_Name,
                        WH_Phone = obj.Phone,
                        WH_Photo = obj.Photo,
                        WH_Spell = obj.Spell,
                        WH_TransDatetime = DateTime.Now
                    };
                    List<W_Warehouse> list = goodsManageBLL.GetWarehouseByPage(info,pager);
                    result.FirstParam = list;
                    result.Status = 1;
                    result.Message = "Request Is Success";
                }
                else
                {
                    result.Status = 0;
                    result.Message = "Missing Required Parameters";
                }
            }
            catch (Exception ex)
            {
                result.Status = 500;
                result.Message = "FuDiController GetWarehouseByPage Server Error";
                Log.Error("FuDiController GetWarehouseByPage ", ex.ToString());
            }
            return result;
        }


        /// <summary>
        ///  物资列表
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost]
        public ResultDto<dynamic> GetGoodsInfo(GoodsInfoReq obj)
        {
            ResultDto<dynamic> result = new ResultDto<dynamic>();
            try
            {
                if (obj != null)
                {
                    W_GoodsInfo info = new W_GoodsInfo()
                    {
                            G_NO = obj.NO,
                            G_ID = obj.ID,
                            WH_ID = obj.WH_ID,
                            WH_Name = obj.WH_Name,
                            G_AllLocation = obj.AllLocation,
                            G_ManufactureDate = obj.ManufactureDate,
                            G_Count = obj.Count,
                            G_TransDatetime = DateTime.Now,
    
                    };
                    List<W_GoodsInfo> list = goodsManageBLL.GetGoodsInfo(info);
                    result.FirstParam = list;
                    result.Status = 1;
                    result.Message = "Request Is Success";
                }
                else
                {
                    result.Status = 0;
                    result.Message = "Missing Required Parameters";
                }
            }
            catch (Exception ex)
            {
                result.Status = 500;
                result.Message = "FuDiController GetGoodsInfo Server Error";
                Log.Error("FuDiController GetGoodsInfo ", ex.ToString());
            }
            return result;
        }


        /// <summary>
        ///  物资列表 分页
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost]
        public ResultDto<dynamic> GetGoodsInfoByPage(GoodsInfoReq obj)
        {
            ResultDto<dynamic> result = new ResultDto<dynamic>();
            try
            {
                if (obj != null)
                {

                    GridPager2 pager = Pickout.GetGridPager2(obj);
                    if (pager.StartTime != null)
                    {
                        pager.StartTime = pager.StartTime.StateTimeConvert();
                    }
                    if (pager.EndTime != null)
                    {
                        pager.EndTime = pager.EndTime.EndTimeConvert();
                    }

                    W_GoodsInfo info = new W_GoodsInfo()
                    {
                        G_NO = obj.NO,
                        G_ID = obj.ID,
                        WH_ID = obj.WH_ID,
                        WH_Name = obj.WH_Name,
                        G_AllLocation = obj.AllLocation,
                        G_ManufactureDate = obj.ManufactureDate,
                        G_Count = obj.Count,
                        G_TransDatetime = DateTime.Now,

                    };
                    List<W_GoodsInfo> list = goodsManageBLL.GetGoodsInfoByPage(info,pager);
                    result.FirstParam = list;

                    result.Status = 1;
                    result.Message = "Request Is Success";
                }
                else
                {
                    result.Status = 0;
                    result.Message = "Missing Required Parameters";
                }
            }
            catch (Exception ex)
            {
                result.Status = 500;
                result.Message = "FuDiController GetGoodsInfoByPage Server Error";
                Log.Error("FuDiController GetGoodsInfoByPage ", ex.ToString());
            }
            return result;
        }



        /// <summary>
        /// 统计--单项统计
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost]
        public ResultDto<dynamic, dynamic> SingleStatistics(SingleStatisticsReq obj)
        {
            ResultDto<dynamic, dynamic> result = new ResultDto<dynamic, dynamic>();
            try
            {
                if (obj != null)
                {

                    if (obj.SelectYear > 0)
                    {
                        obj.Years.Add(obj.SelectYear);
                    }
                    obj.Years = obj.Years.Distinct().OrderByDescending(o => o).ToList();

                    string tempStartTimeSplit = "/01/01 00:00:00";
                    string tempEndTimeSplit = "/12/31 23:59:59";
                    if (obj.StartTime == null)
                    {
                        obj.StartTime = (DateTime.Now.Year + tempStartTimeSplit).ToDateTime();
                    }
                    else
                    {
                        obj.StartTime = obj.StartTime.Value.StateTimeConvert();
                    }

                    if (obj.EndTime == null)
                    {
                        obj.EndTime = (DateTime.Now.Year + tempEndTimeSplit).ToDateTime();
                    }
                    else
                    {
                        obj.EndTime = obj.EndTime.Value.EndTimeConvert();
                    }

                    string exclusiveYearStartTime = obj.StartTime.Value.ToString("/MM/dd HH:mm:ss");
                    string exclusiveYearEndime = obj.EndTime.Value.ToString("/MM/dd HH:mm:ss");

                    //事发地点统计
                    if (obj.StatisticsType == 1)
                    {
                        List<dynamic> csList = new List<dynamic>();
                        if (obj.Years == null || obj.Years.Count == 0)
                        {
                            csList.Add(new { Year = DateTime.Now.Year, Data = fireStatisticsBLL.CountyStatistics(obj.StartTime.Value, obj.EndTime.Value) });
                        }
                        else
                        {
                            for (int i = 0; i < obj.Years.Count; i++)
                            {
                                DateTime tempStartTime = (obj.Years[i] + exclusiveYearStartTime).ToDateTime();
                                DateTime tempEndTime = (obj.Years[i] + exclusiveYearEndime).ToDateTime();
                                csList.Add(new { Year = obj.Years[i], Data = fireStatisticsBLL.CountyStatistics(tempStartTime, tempEndTime) });
                            }
                        }
                        //设置xAxis->data
                        var linList = linchpinBll.GetSubLinchpin(101);//北京
                        string[] linNames = new string[linList == null ? 0 : linList.Count];
                        for (int i = 0; i < linList.Count; i++)
                        {
                            linNames[i] = linList[i].LinchpinName;
                        }

                        result.FirstParam = csList;
                        result.SecondParam = linNames;
                    }
                    //事发时间统计
                    else if (obj.StatisticsType == 2)
                    {
                        List<dynamic> tsList = new List<dynamic>();
                        if (obj.Years == null || obj.Years.Count == 0)
                        {
                            tsList.Add(new { Year = DateTime.Now.Year, Data = fireStatisticsBLL.TimeStatistics(obj.StartTime.Value, obj.EndTime.Value) });
                        }
                        else
                        {
                            for (int i = 0; i < obj.Years.Count; i++)
                            {
                                DateTime tempStartTime = (obj.Years[i] + exclusiveYearStartTime).ToDateTime();
                                DateTime tempEndTime = (obj.Years[i] + exclusiveYearEndime).ToDateTime();
                                tsList.Add(new { Year = obj.Years[i], Data = fireStatisticsBLL.TimeStatistics(tempStartTime, tempEndTime) });
                            }
                        }
                        //设置xAxis->data
                        int[] xAxisTime = new int[24];
                        for (int i = 0; i < xAxisTime.Length; i++)
                        {
                            xAxisTime[i] = i;
                        }
                        result.FirstParam = tsList;
                        result.SecondParam = xAxisTime;

                    }
                    //起火原因
                    else if (obj.StatisticsType == 3)
                    {
                        List<dynamic> fwList = new List<dynamic>();
                        if (obj.Years == null || obj.Years.Count == 0)
                        {
                            fwList.Add(new { Year = DateTime.Now.Year, Data = fireStatisticsBLL.FireWhyStatistics(obj.StartTime.Value, obj.EndTime.Value) });
                        }
                        else
                        {
                            for (int i = 0; i < obj.Years.Count; i++)
                            {
                                DateTime tempStartTime = (obj.Years[i] + exclusiveYearStartTime).ToDateTime();
                                DateTime tempEndTime = (obj.Years[i] + exclusiveYearEndime).ToDateTime();
                                fwList.Add(new { Year = obj.Years[i], Data = fireStatisticsBLL.FireWhyStatistics(tempStartTime, tempEndTime) });
                            }
                        }
                        List<DirectorysTb> dtbList = memberInfoBll.GetDirectorysTb(1);//起火原因

                        result.FirstParam = fwList;
                        result.SecondParam = dtbList;
                    }
                    //报警类型
                    else if (obj.StatisticsType == 4)
                    {
                        List<dynamic> atList = new List<dynamic>();
                        if (obj.Years == null || obj.Years.Count == 0)
                        {
                            atList.Add(new { Year = DateTime.Now.Year, Data = fireStatisticsBLL.AlarmTypeStatistics(obj.StartTime.Value, obj.EndTime.Value) });
                        }
                        else
                        {
                            for (int i = 0; i < obj.Years.Count; i++)
                            {
                                DateTime tempStartTime = (obj.Years[i] + exclusiveYearStartTime).ToDateTime();
                                DateTime tempEndTime = (obj.Years[i] + exclusiveYearEndime).ToDateTime();
                                atList.Add(new { Year = obj.Years[i], Data = fireStatisticsBLL.AlarmTypeStatistics(tempStartTime, tempEndTime) });
                            }
                        }
                        List<DirectorysTb> dtbList = memberInfoBll.GetDirectorysTb(2);//报警方式
                        result.FirstParam = atList;
                        result.SecondParam = dtbList;
                    }
                    //火灾类别
                    else if (obj.StatisticsType == 5)
                    {
                        List<dynamic> fireType = new List<dynamic>();
                        if (obj.Years == null || obj.Years.Count == 0)
                        {
                            fireType.Add(new { Year = DateTime.Now.Year, Data = fireStatisticsBLL.FireTypeStatistics(obj.StartTime.Value, obj.EndTime.Value) });
                        }
                        else
                        {
                            for (int i = 0; i < obj.Years.Count; i++)
                            {
                                DateTime tempStartTime = (obj.Years[i] + exclusiveYearStartTime).ToDateTime();
                                DateTime tempEndTime = (obj.Years[i] + exclusiveYearEndime).ToDateTime();
                                fireType.Add(new { Year = obj.Years[i], Data = fireStatisticsBLL.FireTypeStatistics(tempStartTime, tempEndTime) });
                            }
                        }
                        List<DirectorysTb> dtbList = memberInfoBll.GetDirectorysTb(1023);//火灾类别
                        result.FirstParam = fireType;
                        result.SecondParam = dtbList;
                    }
                    result.Status = 1;
                    result.Message = "Request Is Success";
                }
                else
                {
                    result.Status = 0;
                    result.Message = "Missing Required Parameters";
                }
            }
            catch (Exception ex)
            {
                result.Status = 500;
                result.Message = "FireInfoController SingleStatistics Server Error";
                Log.Error("FireInfoController SingleStatistics ", ex.ToString());
            }
            return result;

        }

        /// <summary>
        /// 获取火灾处置信息
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost]
        public ResultDto<dynamic> GetMRecord(MRecordReq obj)
        {
            ResultDto<dynamic> result = new ResultDto<dynamic>();
            try
            {
                if (obj != null && obj.FireID > 0)
                {
                    //火灾记录处置
                    GridPager2 pager = Pickout.GetGridPager2(obj);
                    pager.PageSize = int.MaxValue;
                    // 2018-06-29 调整 
                    //int searchLevel = 0;
                    //searchLevel = obj.IsCityManager == 1 ? 0 : 1;
                    //List<M_Record> mrList = bll.MRListByFireID(obj.FireID, pager, 0);
                    //List<M_Record> mrList = obj.IsCityManager ==1 ? bll.MRListByFireID(obj.FireID, pager): bll.MRListByFireID(obj.FireID, pager,1);

                    //2018-10-16 调整
                    int searchLevel = obj.IsCityManager == 0 ? 1 : 0;
                    List<M_Record> mrList = bll.MRListByFireID(obj.FireID, pager, searchLevel);


                    result.FirstParam = mrList;
                    result.Status = 1;
                    result.Message = "Request Is Success";
                }
            }
            catch (Exception ex)
            {
                result.Status = 500;
                result.Message = "FireInfoController GetMRecord Server Error";
                Log.Error("FireInfoController GetMRecord", ex.ToString());
            }
            return result;
        }


        /// <summary>
        /// 获取火灾终报信息
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost]
        public ResultDto<dynamic> GetFireFinalReport(FireDetailReq obj)
        {
            ResultDto<dynamic> result = new ResultDto<dynamic>();
            try
            {
                if (obj != null)
                {
                    //获取火灾信息
                    F_FireInfo fireInfo = bll.FireInfoDetail(obj.FireID);

                    List<Linchpin> linchpins = linchpinBll.GetLinchpin(new List<long>()
                                        { fireInfo.F_AddressCounty.ToLong(), fireInfo.F_AddressTown.ToLong(),fireInfo.F_AddressVillage.ToLong()});

                    List<string> linchpinNames = linchpins.Select(s => s.LinchpinName).ToList();

                    List<DirectorysTb> dtbList = memberInfoBll.GetDirectorysTb(0);//0.所有 1.起火原因 2.报警方式 1023.火灾类型
                    var fireWhy = dtbList.Where(p => p.DParentID == 1).ToList();
                    var alarmType = dtbList.Where(p => p.DParentID == 2).ToList();
                    var fireType = dtbList.Where(p => p.DParentID == 1023).ToList();


                    //区县地址和接警时间
                    string fireAddress = string.Join(",", linchpinNames);
                    DateTime alarmTime = fireInfo.F_AlarmTime.Value;


                    //获取前场总指挥
                    var frontCommand = bll.GetFrontCommand(fireInfo.F_FireID).OrderByDescending(o => o.FC_TransDatetime).ToList();
                    string leader = frontCommand != null || frontCommand.Count == 0 ? string.Empty : frontCommand.FirstOrDefault().FC_CommanderName;

                    //报灭时间
                    F_ReportOutFire fireReportOutDetail = bll.FireReportOutDetail(fireInfo.F_FireID);
                    DateTime? reportOutTime = fireReportOutDetail == null ? null : fireReportOutDetail.FR_HandleTime;

                    var data = new { FireAddress = fireAddress, AlarmTime = alarmTime, AlarmType = alarmType, FireWhy = fireWhy, Leader = leader, ReportOutTime = reportOutTime, FireType = fireType };

                    result.FirstParam = data;
                    result.Status = 1;
                    result.Message = "Request Is Success";
                }
                else
                {
                    result.Status = 0;
                    result.Message = "Missing Required Parameters";
                }
            }
            catch (Exception ex)
            {
                result.Status = 500;
                result.Message = "FireInfoController GetApplyRespond Server Error";
                Log.Error("FireInfoController GetApplyRespond ", ex.ToString());
            }
            return result;
        }



        /// <summary>
        /// 根据城市名称 获取城市名称
        /// </summary>
        /// <param name="obj">obj.LinchpinID</param>
        /// <returns></returns>
        [HttpPost]
        public ResultDto<dynamic> GetLinchpin(LinchpinReq obj)
        {
            ResultDto<dynamic> result = new ResultDto<dynamic>();
            try
            {
                int linchpinID = 101;
                if (obj != null && obj.LinchpinID != 0)
                {
                    linchpinID = obj.LinchpinID;
                }

                result.FirstParam = linchpinBll.GetLinchpin(linchpinID);
                result.Status = 1;
                result.Message = "Request Is Success";
            }
            catch (Exception ex)
            {
                result.Status = 500;
                result.Message = "FireInfoController GetLinchpin Server Error";
                Log.Error("FireInfoController GetLinchpin", ex.ToString());
            }
            return result;
        }


        /// <summary>
        /// 根据ID 获取下级城市信息集合 默认获取北京市
        /// </summary>
        /// <param name="obj">obj.LinchpinID</param>
        /// <returns></returns>
        [HttpPost]
        public ResultDto<dynamic> GetSubLinchpin(LinchpinReq obj)
        {
            ResultDto<dynamic> result = new ResultDto<dynamic>();
            try
            {
                int linchpinID = 101;//默认北京市
                if (obj != null && obj.LinchpinID != 0)
                {
                    linchpinID = obj.LinchpinID;
                }
                result.FirstParam = linchpinBll.GetSubLinchpin(linchpinID);
                result.Status = 1;
                result.Message = "Request Is Success";
            }
            catch (Exception ex)
            {
                result.Status = 500;
                result.Message = "FireInfoController GetSubLinchpin Server Error";
                Log.Error("FireInfoController GetSubLinchpin", ex.ToString());
            }
            return result;
        }



        /// <summary>
        /// （消息）获取当前大区未完成火灾列表
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost]
        public ResultDto<dynamic, dynamic> GetUnFinishFire(GlobalAutomaticReq obj)
        {
            ResultDto<dynamic, dynamic> result = new ResultDto<dynamic, dynamic>();
            try
            {
                if (obj != null)
                {
                    string addressCounty = null;
                    if (obj.AddressCounty > 0)
                    {
                        //市局用户获取所有未处理完成的火灾
                        addressCounty = obj.AddressCounty.ToString();
                    }
                    var tempUnFinishFireList = bll.GetFireInfo(addressCounty, 0);
                    List<F_FireInfo> ffList = bll.GetFireInfoFromForce(addressCounty, 0);

                    var unFinishFireList = tempUnFinishFireList.GroupBy(g => new { g.F_FireID, g.F_FireName })
                        .Select(s => new { s.Key.F_FireID, s.Key.F_FireName }).ToList();

                    //本区未完成火灾结果
                    List<dynamic> data = new List<dynamic>();
                    //支援火灾结果
                    List<dynamic> data2 = new List<dynamic>();

                    foreach (var item in unFinishFireList)
                    {
                        data.Add(new { F_FireID = item.F_FireID, F_FireName = item.F_FireName + "流程未完成" });
                    }

                    foreach (var item in ffList)
                    {
                        data2.Add(new { F_FireID = item.F_FireID, F_FireName = item.F_FireName });
                    }
                    result.FirstParam = data;
                    result.SecondParam = data2;
                    result.Status = 1;
                    result.Message = "Request Is Success";
                }
                else
                {
                    result.Status = 0;
                    result.Message = "Missing Required Parameters";
                }
            }
            catch (Exception ex)
            {
                result.Status = 500;
                result.Message = "FireInfoController GetUnFinishFire Server Error";
                Log.Error("FireInfoController GetUnFinishFire ", ex.ToString());
            }
            return result;
        }
    }
}
